#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from flask import Response
from flask_restful import Resource
from src.routers import GetDataFromManager

sys.path.append("../..")


class TMSTileServer(Resource):
    def get(self, servicename, level, column, row, ext):
        tileSize = 256
        serviceType = GetDataFromManager.mapServiceManager.serviceList[servicename]['config']['type']
        if serviceType == 'mbt':
            tileSize = GetDataFromManager.mapServiceManager.serviceList[servicename]['config']['tileSize']
        elif serviceType == 'tpk':
            tileSize = GetDataFromManager.mapServiceManager.serviceList[servicename]['config']['tileSize']

        i = int((int(tileSize)/256)-1)
        row = int(2**(level-i)-row-1)

        resp = ''
        try:
            tile = GetDataFromManager.GetTileFromSLRC(servicename, level, row, column)
            resp = Response(tile['imgData'], status=200, mimetype='image/png')
        except Exception as e:
            print(e)

            resp = Response('MapServer Not Found' +
                            '\n\nlevel:' + str(level) +
                            '\nrow:' + str(row) +
                            '\ncolumn:' + str(column),
                            status=404,
                            mimetype='text/javascript')
        finally:
            return resp
